package App.Filter;

/**
 * Created by xw on 2019/3/6.
 */




/*
 * spring-mvc-logger logs requests/responses
 *
 * Copyright (c) 2013. Israel Zalmanov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import App.Model.BaseEnum;
import App.Model.User;
import App.Service.AccountService;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class LoggingFilter extends OncePerRequestFilter {

    @Autowired
    private AccountService _accountService;

    protected static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);
    private static final String REQUEST_PREFIX = "Request:";
    private static final String RESPONSE_PREFIX = "Response:";
    private AtomicLong id = new AtomicLong(1);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException {

        long requestId = id.incrementAndGet();
        request = new RequestWrapper(requestId, request);
        response = new ResponseWrapper(requestId, response);

        try {
            filterChain.doFilter(request, response);
            //response.flushBuffer();
        } finally {

            logRequest(request);
            logResponse((ResponseWrapper) response);
        }
    }

    private void logRequest(final HttpServletRequest request) {

        StringBuilder msg = new StringBuilder();
        msg.append(REQUEST_PREFIX);
        if (request instanceof RequestWrapper) {
            msg.append("\n");
            msg.append("request id=").append(((RequestWrapper) request).getId()).append(";");
            msg.append("\n");


        }

        String _deviceType = request.getHeader("Device");
        if(_deviceType!=null&&!_deviceType.isEmpty()){

            msg.append("\n");
            msg.append("Device:"+_deviceType);
            msg.append("\n");

        }

        HttpSession session = request.getSession(false);
        if (session != null) {
            msg.append("session id=").append(session.getId()).append(";");
            msg.append("\n");
        }
        if (request.getMethod() != null) {
            msg.append("method=").append(request.getMethod()).append(";");
            msg.append("\n");
        }
        if (request.getContentType() != null) {
            msg.append("content type=").append(request.getContentType()).append(";");
        }
        msg.append("\n");
        msg.append("uri=").append(request.getRequestURI()).append(";");
        msg.append("\n");
        if (request.getQueryString() != null) {
            msg.append('?').append(request.getQueryString());
            msg.append("\n");
        }

        //获取请求主参数
        if (request instanceof RequestWrapper && !isMultipart(request) && !isBinaryContent(request)) {
            RequestWrapper requestWrapper = (RequestWrapper) request;
            try {
                String charEncoding = requestWrapper.getCharacterEncoding() != null ? requestWrapper.getCharacterEncoding() : "UTF-8";
                msg.append(new String(requestWrapper.toByteArray(), charEncoding));
                msg.append("\n");
            } catch (UnsupportedEncodingException e) {
                logger.info("Failed to parse request payload", e);
            }
        }
        String _requestJson = msg.toString();
        logger.info(_requestJson);

        if(request.getRequestURI() != null){
            String _optMethod = request.getRequestURI();
            String _version = request.getHeader("version");
            String _device = request.getHeader("device");
            int _clientTypeInt = BaseEnum.ClientType.getClientTypeStr(_device);
            int _userId = userId();

            if(_version != null && _device != null && _userId > 0){
                _accountService.insertUserLoginHistory(_userId, _version,
                        _clientTypeInt, BaseEnum.ResultType.Success.getResultType(), _optMethod);
            }
        }
    }

    public int userId() {
        int _userId = 0;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) {
            String _princile = auth.getPrincipal().toString();
            if (_princile != null && _princile != "") {
                User _user = JSON.parseObject(_princile, User.class);
                if (_user != null) {
                    _userId = _user.getId();
                }
            }
        }
        return _userId;
    }

    private boolean isBinaryContent(final HttpServletRequest request) {
        if (request.getContentType() == null) {
            return false;
        }
        return request.getContentType().startsWith("image") || request.getContentType().startsWith("video") || request.getContentType().startsWith("audio");
    }

    private boolean isMultipart(final HttpServletRequest request) {
        return request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    }

    private void logResponse(final ResponseWrapper response) {

        StringBuilder msg = new StringBuilder();
        msg.append(RESPONSE_PREFIX);
        msg.append("\n");
        msg.append("request id=").append((response.getId())).append(";");
        msg.append("\n");
        try {
            msg.append(new String(response.toByteArray(), response.getCharacterEncoding()));
            msg.append("\n");
        } catch (UnsupportedEncodingException e) {
            logger.info("Failed to parse response payload", e);
        }
        String _responseJosn = msg.toString();
        logger.info(_responseJosn);
    }

}
